package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * impl wm材料服务
 *
 * @author zhouao
 * @projectName: heima-leadnews
 * @package: com.heima.wemedia.service.impl
 * @className: WmMaterialServiceImpl
 * @author: ZhouAo
 * @description: TODO
 * @date: 2022/6/14 16:51
 * @version: 1.0
 * @date 2022/06/14
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传图片
     *
     * @param multipartFile
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {


        //获取文件输入流
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
            //重新生成文件名
            String name = multipartFile.getOriginalFilename();
            System.out.println("name = " + name);
            log.error(name);
            //文件后缀名
            String substring = name.substring(name.lastIndexOf("."));
            //生成不重复的文件名
            String filename = UUID.randomUUID().toString() + substring;
            //写入文件 获取文件路径
            String path = fileStorageService.uploadImgFile("img", filename, inputStream);
            //将文件路径写入数据库中
            //根据用户登陆的id查询用户信息
            //创建媒体图文素材信息表(WmMaterial)对象
            WmMaterial wm = new WmMaterial();
            Integer id = WmThreadLocalUtil.getUser().getId();
            //填充数据
            wm.setUserId(id);
            wm.setCreatedTime(new Date());
            wm.setType((short) 0);
            wm.setIsCollection((short) 0);
            wm.setUrl(path);
            //保存到数据库
            save(wm);
            ResponseResult.okResult(wm);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
    }

    /**
     * @param wmMaterialDto:
     * @return PageResponseResult
     * @author Administrator
     * @description TODO
     * @date 2022/6/14 17:54
     */
    @Override
    public ResponseResult getList(WmMaterialDto wmMaterialDto) {
        //分页查询
        Page page1 = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        System.out.println("wmMaterialDto = " + wmMaterialDto);
        LambdaQueryWrapper<WmMaterial> query = new LambdaQueryWrapper<>();
        //如果未传递此参数则报参数错误
        if (wmMaterialDto.getIsCollection() == null) {
            PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        query.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId()).eq(WmMaterial::getIsCollection, wmMaterialDto.getIsCollection());
        Page page = this.page(page1, query);

        PageResponseResult result = new PageResponseResult();
        result.setSize(Integer.parseInt(page.getSize() + ""));
        result.setTotal(Integer.parseInt(page.getTotal() + ""));
        result.setData(page.getRecords());
        result.setCurrentPage(wmMaterialDto.getPage());
        result.setErrorMessage("操作成功");
        return result;
    }

    @Autowired
    private WmNewsMaterialMapper mapper;

    @Override
    public ResponseResult del(Integer id) {
        Integer count = mapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count == null) {
            ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //查找数据
        WmMaterial material = getById(id);
        removeById(id);
        fileStorageService.delete(material.getUrl());
        return ResponseResult.okResult("success");
    }
}
